package com.stylefeng.guns.config.handler;

import com.stylefeng.guns.modular.orderpush.controller.OrderController;
import com.stylefeng.guns.modular.orderpush.controller.WebSocketServer;
import com.stylefeng.guns.modular.orderpush.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Logger;

/**
 * Created by brunoli on 2018/5/15.
 */
@Component
public class WsHandler extends TextWebSocketHandler
{
    private static final ArrayList<WebSocketSession> users;//这个会出现性能问题，最好用Map来存储，key用userid
    private static Logger logger = Logger.getLogger(String.valueOf(WsHandler.class));
    static {
        users = new ArrayList<>();
    }

    @Autowired
    IOrderService orderService;


    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception
    {
        super.afterConnectionClosed(session, status);
        System.out.println("close....");
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception
    {
        System.out.println("connect to the websocket success......当前数量:"+users.size());
        users.add(session);
       // System.out.println("建立新的会话");
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception
    {
        System.out.println(message.getPayload());
        TextMessage msg=new TextMessage(message.getPayload());
        session.sendMessage(msg);

    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception
    {

        super.handleMessage(session, message);
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception
    {
        super.handleTransportError(session, exception);
    }


    /**
     * 给所有在线用户发送消息
     *
     * @param message
     */
    public static void sendMessageToUsers(TextMessage message) {
        for (WebSocketSession user : users) {
            try {
                if (user.isOpen()) {
                    TextMessage msg=new TextMessage(message.getPayload());
                    user.sendMessage(msg);
                    System.out.println(message);


                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}